﻿using System;
using System.Reflection;
using ORM.Attribute;

namespace ORM
{
    public class SqlHelper
    {
        public static string GetAdd<T>(T t) where T : ITableObject, new ()
        {
            string sql = "insert into {0}({1}) values({2});";
            string tableName = AttributeHelper.GetTableName<T>();
            PropertyInfo[] infos = typeof (T).GetProperties();
            string[] fieldNames = AttributeHelper.GetFields<T>();
            string[] fieldValues = new string[infos.Length];
            int i = 0;
            FieldAttribute fieldAttr;
            object objValue = null;

            foreach (PropertyInfo info in infos)
            {
                objValue = AttributeHelper.GetPropertyValue<T>(t, info.Name);
                fieldAttr = AttributeHelper.GetPropertyAttribute(info);
                if(null == fieldAttr) continue;
                fieldValues[i++] = GenParasValue((null == objValue) ? "" : objValue.ToString(), fieldAttr.FieldType);
            }
            sql = String.Format(sql, tableName, String.Join( ",",fieldNames), String.Join(",", fieldValues));
            return sql;
        }

        private static string GenParasValue(string values, DbFieldType type)
        {
            string pValue = "";
            switch (type)
            {
                case DbFieldType.TINYINT:
                case DbFieldType.INT:
                    pValue = values;
                    break;
                case DbFieldType.VARCHAR:
                case DbFieldType.NVARCHAR:
                case DbFieldType.DATETIME:
                case DbFieldType.TEXT:
                case DbFieldType.NTEXT:
                case DbFieldType.XML:
                    pValue = String.Format("'{0}'", values);
                    break;
                default:
                    break;
            }
            return pValue;
        }


        public static string GetRemove()
        {
            return "";
        }

        public static string GetUpdate()
        {
            return "";
        }

        public static string GetSearch()
        {
            return "";
        }

        public static string GetList()
        {
            return "";
        }
    }
}
